<?php
/**
 * Created by PhpStorm.
 * User: wudiying
 * Date: 2020/2/6
 * Time: 下午10:07
 */

//$a = range(0,100);
//var_dump(memory_get_usage());
//
//$b = $a;
//var_dump(memory_get_usage());
//
//$b = range(1,200);
//var_dump(memory_get_usage());


//获取视频解密密钥
function DescribeDrmDataKey($edk,$type = "1"){
    $params['edkList.0'] = $edk;
    $prefix = "GET" . "vod.api.qcloud.com/v2/index.php";

    $video_params = getVideoParams('DescribeDrmDataKey', $params, $prefix);

    $curl_url = "https://vod.api.qcloud.com/v2/index.php";
    $curl_url = $curl_url . "?" . http_build_query($video_params);

    $curl_result = curl_send_get_request($curl_url);
    $resultData = json_decode($curl_result, true);

//    var_dump($resultData);
    if ($resultData && $resultData['code'] == 0) {
        $result = $resultData['data']['keyList'][0]['dk'];
    } else {
        $result = $curl_result;
    }

    if ($type == "1"){
        return base64_decode($result);
    }
    return $result;

}


function getVideoParams($action, $params, $prefix) {

    // development
    $secretId = "AKIDVt76qM8ePuFKAkIA2e0B6lAJDuMYxOxG";
    $secretKey = "DDxRfhTzFExQccQzIK6kANK7dttc5IGy";
    $region = "gz";


    // production
    $secretId = "AKIDGUjcKsgFE7lGbnh4LYgpLjx4zkmot7zg";
    $secretKey = "tENNFvQjrpfbONabCd1FWvAF80e3ED1a";
    $region = "sh";


    /*下面这五个参数为所有接口的 公共参数；对于某些接口没有地域概念，则不用传递Region（如DescribeDeals）*/
    $COMMON_PARAMS = [
        'Nonce'     => rand(),
        'Timestamp' => time(),
        'Action'    => $action,
        'SecretId'  => $secretId,
        'Region'    => $region
    ];
    $COMMON_PARAMS = array_merge($COMMON_PARAMS, $params);

//    $secretKey = $secretKey;

    $signature = getSignature($prefix, $COMMON_PARAMS, $secretKey);

    $COMMON_PARAMS['Signature'] = $signature;

    return $COMMON_PARAMS;
}

function getSignature($prefix, $params, $secretKey) {

    /***************对请求参数 按参数名 做字典序升序排列，注意此排序区分大小写*************/
    ksort($params);

    /**********************************生成签名原文**********************************
     * 将 请求方法, URI地址,及排序好的请求参数  按照下面格式  拼接在一起, 生成签名原文，此请求中的原文为
     * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz
     * &SecretId=AKIDz8krbsJ5yKBZQ    ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141
     * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789
     * ****************************************************************************/

    $SigTxt = $prefix . "?";

    $isFirst = true;
    foreach ($params as $key => $value) {
        if (!$isFirst) {
            $SigTxt = $SigTxt . "&";
        }
        $isFirst = false;

        /*拼接签名原文时，如果参数名称中携带_，需要替换成.*/
        if (strpos($key, '_')) {
            $key = str_replace('_', '.', $key);
        }

        $SigTxt = $SigTxt . $key . "=" . $value;
    }

    /*********************根据签名原文字符串 $SigTxt，生成签名 Signature******************/
    $signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true));

    return $signature;
}